<template>
  <div class="divBox relative">
    <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: 0 }">
      <div class="padding-add">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
          <el-form-item label="门店名称" prop="roomName">
            <el-input
              v-model="queryParams.roomName"
              placeholder="请输入门店名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="门店地址" prop="roomAdress">
            <el-input
              v-model="queryParams.roomAdress"
              placeholder="请输入门店地址"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="门店联系电话" prop="roomPhone">
            <el-input
              v-model="queryParams.roomPhone"
              placeholder="请输入门店联系电话"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="门店营业时间" prop="roomJobTimeRange">
            <el-time-picker
              v-model="queryParams.roomJobTimeRange"
              is-range
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="请选择营业时间范围"
              style="width: 220px"
            />
          </el-form-item>
          <el-form-item label="门店经纬度定位" prop="roomPosition">
            <el-input
              v-model="queryParams.roomPosition"
              placeholder="请输入门店经纬度定位"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="门店负责人" prop="roomManager">
            <el-input
              v-model="queryParams.roomManager"
              placeholder="请输入门店负责人"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="box-card mt14" :body-style="{ padding: '20px 20px' }" shadow="never" :bordered="false">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['platform:room:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['platform:room:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['platform:room:remove']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['platform:room:export']"
            >导出</el-button
          >
        </el-col>
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
      </el-row>

      <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="门店编号" align="center" prop="id" />
        <el-table-column label="门店名称" align="center" prop="roomName" />
        <el-table-column label="门店所在城市" align="center" prop="city" />
        <el-table-column label="门店地址" align="center" prop="roomAdress" />
        <el-table-column label="门店联系电话" align="center" prop="roomPhone" />
        <el-table-column label="门店账号" align="center" prop="roomAccount" />
        <el-table-column label="门店营业时间" align="center" prop="roomJobTime" />
        <el-table-column label="门店经纬度定位" align="center" prop="roomPosition" />
        <el-table-column label="门店负责人" align="center" prop="roomManager" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['platform:room:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['platform:room:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.limit"
        @size-change="limitChange"
        @current-change="paginationChange"
      />
    </el-card>

    <!-- 添加或修改门店信息主对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="860px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="custom-form">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="门店名称" prop="roomName">
              <el-input v-model="form.roomName" placeholder="请输入门店名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店类型" prop="roomType">
              <el-select v-model="form.roomType" placeholder="请选择门店类型">
                <el-option label="直营店" :value="1" />
                <el-option label="加盟店" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店编号" prop="roomNumber">
              <el-input v-model="form.roomNumber" placeholder="请输入门店编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店账号" prop="roomAccount">
              <el-input v-model="form.roomAccount" placeholder="请输入门店账号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店负责人" prop="roomManager">
              <el-input v-model="form.roomManager" placeholder="请输入门店负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="roomPhone">
              <el-input v-model="form.roomPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号密码" prop="roomPassword">
              <el-input v-model="form.roomPassword" placeholder="请输入账号密码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业时间" prop="roomJobTimeBegin, roomJobTimeEnd" :key="form.roomJobTimeBegin">
              <el-time-select v-if="open" @blur="handleChange"
                v-model="form.roomJobTimeBegin"
                placeholder="开始时间"
                format="HH:mm"
                value-format="HH:mm"
                style="width: 136px"
                :clearable="false"
                :picker-options="{
                  step: '00:10',
                  start: '00:00',
                  end: '23:59'
                }"
                
              />
              <span style="margin: 0 8px;">-</span>
              <el-time-select v-if="open"
                v-model="form.roomJobTimeEnd"
                placeholder="结束时间"
                format="HH:mm"
                value-format="HH:mm"
                style="width: 136px"
                :clearable="false"
                :picker-options="{
                  step: '00:10',
                  start: '00:00',
                  end: '23:59'
                }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店城市" prop="citys">
              <el-cascader
                v-model="form.citys"
                :options="regionData"
                :props="{ expandTrigger: 'hover', checkStrictly: true }"
                placeholder="请选择所在地区"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地图位置" prop="roomPosition">
              <el-input v-model="form.roomPosition" placeholder="请选择地图位置" style="width: 70%" />
              <el-button @click="showMapDialog = true" style="margin-left: 8px">选择位置</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="roomAdress">
              <el-input v-model="form.roomAdress" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送范围" prop="deliveryDistance">
              <el-input v-model="form.deliveryDistance" placeholder="请选择配送半径（公里）" type="number"  style="width: 70%" />
              <el-button @click="showDeliveryMapDialog = true" :disabled="!form.deliveryDistance" style="margin-left: 8px">选择范围</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店状态" prop="roomStatus">
              <el-switch v-model="form.roomStatus" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注说明" prop="remarks">
              <el-input v-model="form.remarks" placeholder="请输入备注说明" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer custom-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <MapDialog v-model="showMapDialog" :position="form.roomPosition" @select="onMapSelect" v-if="showMapDialog" />


    <DeliveryMapDialog
      :visible.sync="showDeliveryMapDialog"
      v-if="showDeliveryMapDialog"
      :center="form.roomPosition"
      :radius="form.deliveryDistance * 1"
      @select="onDeliveryRangeSelect"
      :polygons="form.deliveryRangeList"
      @clearPolygons="form.deliveryRangeList = []"
      :roomPosition="form.roomPosition"
      :rangeList="rangeList"
    />
  </div>
</template>

<script>
import { listRoom, getRoom, delRoom, addRoom, updateRoom, listRoomDeliveryRange} from '@/api/room';
import { regionData } from 'element-china-area-data';
import MapDialog from '@/components/MapDialog.vue';
import DeliveryMapDialog from '@/components/DeliveryMapDialog.vue';

export default {
  name: 'Room',
  components: { MapDialog, DeliveryMapDialog },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店信息主表格数据
      roomList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 地区数据
      regionData: regionData,
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        roomName: null,
        roomAdress: null,
        roomPhone: null,
        roomJobTimeRange: [],
        roomPosition: null,
        roomManager: null,
        citys: [],
      },
      // 表单参数
      form: {
        id: null,
        roomName: null,
        roomType: null, // 门店类型
        roomNumber: null, // 门店编号
        roomManager: null, // 门店负责人
        roomPhone: null, // 联系电话
        roomPassword: null, // 账号密码
        roomJobTime: null, // 营业时间
        roomJobTimeBegin: null, // 营业开始时间
        roomJobTimeEnd: null,   // 营业结束时间
        citys: [], // 门店城市（级联选择）
        city: null, // 门店城市（最终值）
        roomPosition: null, // 地图位置
        roomAdress: null, // 详细地址
        deliveryDistance: null, // 配送距离
        deliveryRangeList: [], // 配送范围
        roomStatus: 1, // 门店状态（开关）
        remarks: null, // 备注说明
        roomAccount: null,
      },
      // 表单校验
      rules: {
        roomName: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
        roomType: [{ required: true, message: '请选择门店类型', trigger: 'change' }],
        roomNumber: [{ required: true, message: '请输入门店编号', trigger: 'blur' }],
        roomAccount: [{ required: true, message: '请输入门店账号', trigger: 'blur' }],
        roomManager: [{ required: true, message: '请输入门店负责人', trigger: 'blur' }],
        roomPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        roomPassword: [{ required: true, message: '请输入账号密码', trigger: 'blur' }],
        roomJobTimeBegin: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        roomJobTimeEnd: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
        citys: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
        roomPosition: [{ required: true, message: '请输入地图位置', trigger: 'blur' }],
        roomAdress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
        deliveryDistance: [{ required: true, message: '请输入配送半径', trigger: 'change' }],
        roomStatus: [{ required: true, message: '请选择门店状态', trigger: 'change' }],
      },
      showMapDialog: false,
      showDeliveryMapDialog: false,
      rangeList:[]
    };
  },
  created() {
    this.getList();
    this.getRangeList()
  },
 
  methods: {
    handleChange(e){
      console.log(e, 548);
      // this.form.roomJobTimeBegin = e.target.value
    },
    getRangeList() { 
      listRoomDeliveryRange().then((res) => {
        console.log(res,369);
        this.rangeList = res;
      });
    },

    limitChange(limit) {
      console.log(limit, 329);
      
      this.queryParams.limit = limit;
      this.getList();
    },
    paginationChange(page) {
      console.log(page, 251);
      this.queryParams.page = page;
      this.getList();
    },
    /** 查询门店信息主列表 */
    getList() {
      this.loading = true;
      listRoom(this.queryParams).then((response) => {
        this.roomList = response.list;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        roomName: null,
        roomType: null,
        roomNumber: null,
        roomManager: null,
        roomPhone: null,
        roomPassword: null,
        roomJobTime: null,
        roomJobTimeBegin: null,
        roomJobTimeEnd: null,
        citys: [],
        city: null,
        roomPosition: null,
        roomAdress: null,
        deliveryDistance: null,
        roomStatus: 1,
        remarks: null,
        deliveryRangeList: [],
        roomAccount: null
      };
      this.resetForm('form');
    },

    /** 搜索按钮操作 */
    handleQuery() {
      // 查询前处理营业时间范围
      if (this.queryParams.roomJobTimeRange && this.queryParams.roomJobTimeRange.length === 2) {
        this.queryParams.roomJobTime = this.queryParams.roomJobTimeRange.join(' - ');
      } else {
        this.queryParams.roomJobTime = '';
      }
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.queryParams.roomJobTimeRange = [];
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加门店信息';
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getRoom(id).then((response) => {
        console.log(response)
        Object.assign(this.form, response);
        // Find the matching city path in regionData
        const findCityPath = (data, targetCity) => {
          for (let item of data) {
            if (item.label === targetCity) {
              return [item.value];
            }
            if (item.children) {
              const path = findCityPath(item.children, targetCity);
              if (path) {
                return [item.value, ...path];
              }
            }
          }
          return null;
        };

        if (response.city) {
          const cityPath = findCityPath(this.regionData, response.city);
          if (cityPath) {
            this.form.citys = cityPath;
          }
        }

        // 回显营业时间
        if (response.roomJobTime) {
          const timeParts = response.roomJobTime.split(' - ');
          console.log(timeParts, 506);
          if (timeParts.length === 2) {
            this.form.roomJobTimeBegin = timeParts[0].trim();
            this.form.roomJobTimeEnd = timeParts[1].trim();
          }
        }
        this.open = true;
        this.title = '修改门店信息';
        console.log(this.form.roomJobTimeBegin, this.form.roomJobTimeEnd)
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const formData = { ...this.form };
          // 处理城市
          if (formData.citys && formData.citys.length > 0) {
            let currentNode = this.regionData;
            let lastLabel = '';
            for (const value of formData.citys) {
              const found = currentNode.find((item) => item.value === value);
              if (found) {
                lastLabel = found.label;
                currentNode = found.children || [];
              }
            }
            formData.city = lastLabel;
          }
          // 处理营业时间
          if (formData.roomJobTimeBegin && formData.roomJobTimeEnd) {
            formData.roomJobTime = `${formData.roomJobTimeBegin} - ${formData.roomJobTimeEnd}`;
          } else {
            formData.roomJobTime = '';
          }
          delete formData.roomJobTimeBegin;
          delete formData.roomJobTimeEnd;
          delete formData.citys;
          if (this.form.id != null) {
            updateRoom(formData).then((response) => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
              this.getRangeList()
            });
          } else {
            addRoom(formData).then((response) => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
              this.getRangeList()
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除门店信息主编号为"' + ids + '"的数据项？')
        .then(function () {
          return delRoom(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'platform/room/export',
        {
          ...this.queryParams,
        },
        `room_${new Date().getTime()}.xlsx`,
      );
    },
    onMapSelect(lnglat, address) {
      this.form.roomPosition = lnglat;
      this.form.roomAdress = address;
    },
    onDeliveryRangeSelect(val) {
      console.log(val.polygon, 548);
      this.form.deliveryRangeList = val.polygon;
      // this.form.roomPosition = val.center;
      // this.form.deliveryDistance = (val.radius / 1000).toFixed(2);
    },
  },
};
</script>

<style scoped>
.custom-form .el-form-item {
  margin-bottom: 20px;
}
.custom-form .el-input,
.custom-form .el-select,
.custom-form .el-cascader {
  width: 100%;
}
.custom-form .el-input__inner::placeholder {
  color: #bfbfbf;
}
.custom-form .el-form-item__label {
  font-weight: 500;
  color: #333;
}
.custom-footer {
  text-align: center;
}
.custom-footer .el-button {
  min-width: 90px;
  border-radius: 4px;
  margin: 0 8px;
}
</style>
